package com.jiehoo.elove.util;

import java.io.*;

public class StringUtils {
	public static final String LINE_SEPARATOR = System
			.getProperty("line.separator");

	public static String getNamePart(String filename) {
		int index = filename.lastIndexOf(".");
		if (index >= 0) {
			return filename.substring(0, index);
		} else {
			return filename;
		}
	}

	public static boolean isEmpty(String string) {
		if (string == null || string.trim().length() == 0) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean contains(String original, String flag) {
		if (original.indexOf(flag) >= 0) {
			return true;
		} else {
			return false;
		}
	}

	public static void printStrings(String[][] strings, String delim,
			OutputStream out) {
		if (strings != null && strings.length > 0) {
			for (int i = 0; i < strings.length; i++) {
				printStrings(strings[i], delim, out);
			}
		} else {
			try {
				out.write("null".getBytes());
				out.write(LINE_SEPARATOR.getBytes());
			} catch (IOException e) {

			}
		}
	}

	public static void printStrings(String[] strings, String delim,
			OutputStream out) {
		try {
			if (strings != null && strings.length > 0) {
				int length = strings.length - 1;
				for (int i = 0; i < length; i++) {
					if (strings[i] != null) {
						if (strings[i].indexOf(delim) > -1) {
							out.write(("\"" + strings[i] + "\"" + delim)
									.getBytes());
						} else {
							out.write((strings[i] + delim).getBytes());
						}
					} else {
						out.write("null".getBytes());
					}
				}
				if (strings[length] != null) {
					if (strings[length].indexOf(delim) > -1) {
						out.write(("\"" + strings[length] + "\"").getBytes());
					} else {
						out.write(strings[length].getBytes());
					}
				} else {
					out.write("null".getBytes());
				}
			} else {
				out.write("null".getBytes());
			}
			out.write(LINE_SEPARATOR.getBytes());
		} catch (IOException e) {

		}
	}

	public static String getFileContent(File file) {
		BufferedReader reader = null;
		StringBuffer content = new StringBuffer(1024);
		try {
			reader = new BufferedReader(new java.io.FileReader(file));
			String line = reader.readLine();
			while (line != null) {
				content.append(line);
				line = reader.readLine();
			}
			return content.toString();
		} catch (IOException e) {
			System.err.println(e.getMessage());
			return "";
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException ioe) {
					System.err.println(ioe.getMessage());
					return content.toString();
				}
			}
		}
	}
}